<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>志愿者服务履历管理</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            text-align: center;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input, textarea, select {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        textarea {
            height: 80px;
            resize: vertical;
        }
        .btn {
            background-color: #007bff;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 10px;
        }
        .btn:hover {
            background-color: #0056b3;
        }
        .btn-danger {
            background-color: #dc3545;
        }
        .btn-danger:hover {
            background-color: #c82333;
        }
        .btn-warning {
            background-color: #ffc107;
            color: #212529;
        }
        .btn-warning:hover {
            background-color: #e0a800;
        }
        .btn-info {
            background-color: #17a2b8;
        }
        .btn-info:hover {
            background-color: #138496;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        th {
            background-color: #f8f9fa;
            font-weight: bold;
        }
        tr:hover {
            background-color: #f5f5f5;
        }
        .action-buttons {
            white-space: nowrap;
        }
        .form-container {
            background-color: #f8f9fa;
            padding: 20px;
            border-radius: 4px;
            margin-bottom: 20px;
        }
        .hidden {
            display: none;
        }
        .search-container {
            margin-bottom: 20px;
            padding: 15px;
            background-color: #e9ecef;
            border-radius: 4px;
        }
        .search-group {
            display: inline-block;
            margin-right: 15px;
        }
    </style>
</head>
<body>
<div class="container">
    <h1>志愿者服务履历管理</h1>

    <!-- 搜索区域 -->
    <div class="search-container">
        <div class="search-group">
            <label for="searchUserId">用户ID:</label>
            <input type="number" id="searchUserId" placeholder="请输入用户ID">
        </div>
        <div class="search-group">
            <label for="searchActivityId">活动ID:</label>
            <input type="number" id="searchActivityId" placeholder="请输入活动ID">
        </div>
        <button class="btn" id="searchBtn">搜索</button>
        <button class="btn btn-warning" id="resetSearchBtn">重置</button>
    </div>

    <!-- 添加/编辑表单 -->
    <div class="form-container" id="volunteerResumeForm">
        <h2 id="formTitle">添加服务履历</h2>
        <form id="resumeForm">
            <input type="hidden" id="resumeId" name="resumeId">
            <div class="form-group">
                <label for="userId">用户ID:</label>
                <input type="number" id="userId" name="userId" required>
            </div>
            <div class="form-group">
                <label for="activityId">活动ID:</label>
                <input type="number" id="activityId" name="activityId" required>
            </div>
            <div class="form-group">
                <label for="activityTitle">活动标题:</label>
                <input type="text" id="activityTitle" name="activityTitle" required>
            </div>
            <div class="form-group">
                <label for="serviceTime">服务时间:</label>
                <input type="datetime-local" id="serviceTime" name="serviceTime">
            </div>
            <div class="form-group">
                <label for="serviceHours">服务时长(小时):</label>
                <input type="number" id="serviceHours" name="serviceHours" step="0.1" min="0">
            </div>
            <div class="form-group">
                <label for="remark">活动评价:</label>
                <textarea id="remark" name="remark"></textarea>
            </div>
            <button type="submit" class="btn" id="saveBtn">保存</button>
            <button type="button" class="btn btn-warning" id="cancelBtn">取消</button>
        </form>
    </div>

    <!-- 操作按钮 -->
    <div>
        <button class="btn" id="refreshBtn">刷新列表</button>
        <button class="btn" id="addBtn">添加履历</button>
    </div>

    <!-- 服务履历列表 -->
    <table id="volunteerResumeTable">
        <thead>
        <tr>
            <th>ID</th>
            <th>用户ID</th>
            <th>活动ID</th>
            <th>活动标题</th>
            <th>服务时间</th>
            <th>服务时长</th>
            <th>活动评价</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody id="volunteerResumeList">
        <!-- 数据将通过JavaScript动态加载 -->
        </tbody>
    </table>
</div>

<script>
    // 全局变量
    const apiUrl = '/volunteer-resumes';
    let isEditing = false;

    // DOM元素
    const formContainer = document.getElementById('volunteerResumeForm');
    const formTitle = document.getElementById('formTitle');
    const resumeForm = document.getElementById('resumeForm');
    const resumeIdInput = document.getElementById('resumeId');
    const userIdInput = document.getElementById('userId');
    const activityIdInput = document.getElementById('activityId');
    const activityTitleInput = document.getElementById('activityTitle');
    const serviceTimeInput = document.getElementById('serviceTime');
    const serviceHoursInput = document.getElementById('serviceHours');
    const remarkInput = document.getElementById('remark');
    const saveBtn = document.getElementById('saveBtn');
    const cancelBtn = document.getElementById('cancelBtn');
    const refreshBtn = document.getElementById('refreshBtn');
    const addBtn = document.getElementById('addBtn');
    const volunteerResumeList = document.getElementById('volunteerResumeList');
    const searchUserId = document.getElementById('searchUserId');
    const searchActivityId = document.getElementById('searchActivityId');
    const searchBtn = document.getElementById('searchBtn');
    const resetSearchBtn = document.getElementById('resetSearchBtn');

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
        loadVolunteerResumes();
    });

    // 绑定事件监听器
    addBtn.addEventListener('click', showAddForm);
    cancelBtn.addEventListener('click', cancelEdit);
    refreshBtn.addEventListener('click', loadVolunteerResumes);
    resumeForm.addEventListener('submit', saveVolunteerResume);
    searchBtn.addEventListener('click', searchVolunteerResumes);
    resetSearchBtn.addEventListener('click', resetSearch);

    // 加载所有服务履历
    function loadVolunteerResumes() {
        fetch(apiUrl)
            .then(response => response.json())
            .then(data => {
                renderVolunteerResumes(data);
            })
            .catch(error => {
                console.error('加载服务履历失败:', error);
                alert('加载服务履历失败');
            });
    }

    // 搜索服务履历
    function searchVolunteerResumes() {
        const userId = searchUserId.value;
        const activityId = searchActivityId.value;

        let url = apiUrl;
        if (userId) {
            url = `${apiUrl}/user/${userId}`;
        } else if (activityId) {
            url = `${apiUrl}/activity/${activityId}`;
        }

        fetch(url)
            .then(response => response.json())
            .then(data => {
                renderVolunteerResumes(data);
            })
            .catch(error => {
                console.error('搜索服务履历失败:', error);
                alert('搜索服务履历失败');
            });
    }

    // 重置搜索
    function resetSearch() {
        searchUserId.value = '';
        searchActivityId.value = '';
        loadVolunteerResumes();
    }

    // 渲染服务履历列表
    function renderVolunteerResumes(volunteerResumes) {
        volunteerResumeList.innerHTML = '';

        if (!volunteerResumes || volunteerResumes.length === 0) {
            const row = document.createElement('tr');
            row.innerHTML = '<td colspan="8" style="text-align: center;">暂无数据</td>';
            volunteerResumeList.appendChild(row);
            return;
        }

        volunteerResumes.forEach(resume => {
            const row = document.createElement('tr');
            row.innerHTML = `
                    <td>${resume.resume_id || ''}</td>
                    <td>${resume.user_id || ''}</td>
                    <td>${resume.activity_id || ''}</td>
                    <td>${resume.activity_title || ''}</td>
                    <td>${formatDateTime(resume.service_time) || ''}</td>
                    <td>${resume.service_hours || ''}</td>
                    <td>${resume.remark || ''}</td>
                    <td class="action-buttons">
                        <button class="btn" onclick="editVolunteerResume(${JSON.stringify(resume)})">编辑</button>
                        <button class="btn btn-danger" onclick="deleteVolunteerResume(${resume.resume_id})">删除</button>
                    </td>
                `;
            volunteerResumeList.appendChild(row);
        });
    }

    // 格式化日期时间
    function formatDateTime(dateTimeStr) {
        if (!dateTimeStr) return '';
        const date = new Date(dateTimeStr);
        return date.toLocaleString('zh-CN');
    }

    // 显示添加表单
    function showAddForm() {
        resetForm();
        formTitle.textContent = '添加服务履历';
        formContainer.classList.remove('hidden');
        isEditing = false;
    }

    // 编辑服务履历
    function editVolunteerResume(volunteerResume) {
        resumeIdInput.value = volunteerResume.resume_id || '';
        userIdInput.value = volunteerResume.user_id || '';
        activityIdInput.value = volunteerResume.activity_id || '';
        activityTitleInput.value = volunteerResume.activity_title || '';
        serviceTimeInput.value = formatDateTimeForInput(volunteerResume.service_time) || '';
        serviceHoursInput.value = volunteerResume.service_hours || '';
        remarkInput.value = volunteerResume.remark || '';

        formTitle.textContent = '编辑服务履历';
        formContainer.classList.remove('hidden');
        isEditing = true;
    }

    // 格式化日期时间用于输入框
    function formatDateTimeForInput(dateTimeStr) {
        if (!dateTimeStr) return '';
        const date = new Date(dateTimeStr);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        return `${year}-${month}-${day}T${hours}:${minutes}`;
    }

    // 取消编辑
    function cancelEdit() {
        resetForm();
        formContainer.classList.add('hidden');
    }

    // 重置表单
    function resetForm() {
        resumeForm.reset();
        resumeIdInput.value = '';
        isEditing = false;
    }

    // 保存服务履历
    function saveVolunteerResume(event) {
        event.preventDefault();

        const volunteerResume = {
            resume_id: resumeIdInput.value ? parseInt(resumeIdInput.value) : null,
            user_id: parseInt(userIdInput.value),
            activity_id: parseInt(activityIdInput.value),
            activity_title: activityTitleInput.value,
            service_time: serviceTimeInput.value ? new Date(serviceTimeInput.value).toISOString() : null,
            service_hours: serviceHoursInput.value ? parseFloat(serviceHoursInput.value) : null,
            remark: remarkInput.value
        };

        if (!volunteerResume.user_id || !volunteerResume.activity_id || !volunteerResume.activity_title) {
            alert('请填写必填字段');
            return;
        }

        const method = isEditing ? 'PUT' : 'POST';
        const url = isEditing ? `${apiUrl}/${volunteerResume.resume_id}` : apiUrl;

        fetch(url, {
            method: method,
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(volunteerResume)
        })
            .then(response => {
                if (response.ok) {
                    return response.json();
                } else {
                    throw new Error('保存失败');
                }
            })
            .then(() => {
                alert(isEditing ? '更新成功' : '添加成功');
                cancelEdit();
                loadVolunteerResumes();
            })
            .catch(error => {
                console.error('保存失败:', error);
                alert('保存失败: ' + error.message);
            });
    }

    // 删除服务履历
    function deleteVolunteerResume(resumeId) {
        if (!confirm('确定要删除这个服务履历吗？')) {
            return;
        }

        fetch(`${apiUrl}/${resumeId}`, {
            method: 'DELETE'
        })
            .then(response => {
                if (response.ok) {
                    alert('删除成功');
                    loadVolunteerResumes();
                } else {
                    throw new Error('删除失败');
                }
            })
            .catch(error => {
                console.error('删除失败:', error);
                alert('删除失败: ' + error.message);
            });
    }

    // 将函数暴露到全局作用域
    window.editVolunteerResume = editVolunteerResume;
    window.deleteVolunteerResume = deleteVolunteerResume;
</script>
</body>
</html>
